package com.city.java.orders.service.impl;

import com.city.java.base.utils.PageVO;
import com.city.java.orders.mapper.OrderMapper;
import com.city.java.orders.pojo.entity.Orders;
import com.city.java.base.response.JsonResult;
import com.city.java.base.response.StatusCode;
import com.city.java.orders.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public JsonResult addOrder(Orders order) {
        log.debug("准备添加订单: {}", order);

        // 参数校验
        if (order == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "订单信息不能为空");
        }

        if (order.getProductId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品ID不能为空");
        }

        if (order.getUserId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        // 设置创建时间（设为当前时间）
        order.setCreatedAt(LocalDateTime.now());

        // 设置默认支付状态
        if (order.getPaymentStatus() == null) {
            order.setPaymentStatus(Orders.PaymentStatus.PENDING);
        }

        try {
            orderMapper.insertOrder(order);
            log.info("订单添加成功: 订单ID={}", order.getOrderId());
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("添加订单失败: 商品ID={}, 用户ID={}", order.getProductId(), order.getUserId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "添加订单失败");
        }
    }

    @Override
    public JsonResult getOrderById(Long orderId) {
        log.debug("根据ID查询订单: {}", orderId);

        // 参数校验
        if (orderId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "订单ID不能为空");
        }

        try {
            Orders order = orderMapper.selectById(orderId);
            if (order != null) {
                log.info("查询订单成功: ID={}", orderId);
                return JsonResult.ok(order);
            } else {
                log.warn("订单不存在: ID={}", orderId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "订单不存在");
            }
        } catch (Exception e) {
            log.error("查询订单失败: ID={}", orderId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单失败");
        }
    }

    @Override
    public JsonResult getAllOrders() {
        log.debug("查询所有订单列表");

        try {
            List<Orders> orders = orderMapper.selectAll();
            log.info("查询所有订单列表成功: 订单数量={}", orders.size());
            return JsonResult.ok(orders);
        } catch (Exception e) {
            log.error("查询所有订单列表失败", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单列表失败");
        }
    }

    @Override
    public JsonResult getOrdersByUserId(Long userId) {
        log.debug("根据用户ID查询订单列表: {}", userId);

        // 参数校验
        if (userId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        try {
            List<Orders> orders = orderMapper.selectByUserId(userId);
            log.info("查询用户订单列表成功: 用户ID={}, 订单数量={}", userId, orders.size());
            return JsonResult.ok(orders);
        } catch (Exception e) {
            log.error("查询用户订单列表失败: 用户ID={}", userId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单列表失败");
        }
    }

    @Override
    public JsonResult getOrdersByProductId(Long productId) {
        log.debug("根据商品ID查询订单列表: {}", productId);

        // 参数校验
        if (productId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品ID不能为空");
        }

        try {
            List<Orders> orders = orderMapper.selectByProductId(productId);
            log.info("查询商品订单列表成功: 商品ID={}, 订单数量={}", productId, orders.size());
            return JsonResult.ok(orders);
        } catch (Exception e) {
            log.error("查询商品订单列表失败: 商品ID={}", productId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单列表失败");
        }
    }

    @Override
    public JsonResult getOrdersByProductName(String productName) {
        log.debug("根据商品名称查询订单列表: {}", productName);

        // 参数校验
        if (productName == null || productName.trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品名称不能为空");
        }

        try {
            List<Orders> orders = orderMapper.selectByProductName(productName);
            log.info("查询商品名称订单列表成功: 商品名称={}, 订单数量={}", productName, orders.size());
            return JsonResult.ok(orders);
        } catch (Exception e) {
            log.error("查询商品名称订单列表失败: 商品名称={}", productName, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单列表失败");
        }
    }

    @Override
    public JsonResult getOrdersByDateRange(LocalDateTime startTime, LocalDateTime endTime) {
        log.debug("根据订单创建时间范围查询订单列表: startTime={}, endTime={}", startTime, endTime);

        try {
            List<Orders> orders = orderMapper.selectByDateRange(startTime, endTime);
            log.info("查询订单创建时间范围列表成功: 开始时间={}, 结束时间={}, 订单数量={}",
                    startTime, endTime, orders.size());
            return JsonResult.ok(orders);
        } catch (Exception e) {
            log.error("查询订单创建时间范围列表失败: 开始时间={}, 结束时间={}", startTime, endTime, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询订单列表失败");
        }
    }

    @Override
    public PageVO<Orders> getOrdersByConditions(String productName, LocalDateTime startTime, LocalDateTime endTime,Integer pageNum,Integer pageSize) {
        PageVO<Orders> list = new PageVO<>();
        pageNum = PageVO.build(pageNum, pageSize);
        Long totalPage;

        try {
            List<Orders> orders = orderMapper.selectByConditions(productName, startTime, endTime,pageNum,pageSize);
            totalPage = orderMapper.getTotal(productName, startTime, endTime);
            list.setList(orders);
            list.setTotalPage(totalPage);

            return list;
        } catch (Exception e) {
            log.error("查询商品名称和时间范围订单列表失败: 商品名称={}, 开始时间={}, 结束时间={}",
                    productName, startTime, endTime, e);
            throw new RuntimeException();
        }
    }

    @Override
    public JsonResult deleteOrderById(Long orderId) {
        log.debug("根据ID删除订单: {}", orderId);

        // 参数校验
        if (orderId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "订单ID不能为空");
        }

        try {
            int result = orderMapper.deleteById(orderId);
            if (result > 0) {
                log.info("删除订单成功: ID={}", orderId);
                return JsonResult.ok();
            } else {
                log.warn("删除订单失败，订单不存在: ID={}", orderId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "订单不存在");
            }
        } catch (Exception e) {
            log.error("删除订单失败: ID={}", orderId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除订单失败");
        }
    }

    @Override
    public JsonResult updateOrder(Orders order) {
        log.debug("更新订单信息: {}", order);

        // 参数校验
        if (order == null || order.getOrderId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "订单ID不能为空");
        }

        try {
            // 检查订单是否存在
            Orders existingOrder = orderMapper.selectById(order.getOrderId());
            if (existingOrder == null) {
                log.warn("更新订单失败，订单不存在: ID={}", order.getOrderId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "订单不存在");
            }

            // 处理支付状态和支付时间的逻辑关系
            // 如果支付状态为已支付但支付时间为空，则设置为当前时间
            if (order.getPaymentStatus() == Orders.PaymentStatus.PAID && order.getPaymentTime() == null) {
                order.setPaymentTime(LocalDateTime.now());
            }
            // 如果支付状态不是已支付，则清空支付时间
            else if (order.getPaymentStatus() != Orders.PaymentStatus.PAID) {
                order.setPaymentTime(null);
            }

            int result = orderMapper.updateById(order);
            if (result > 0) {
                log.info("更新订单成功: ID={}", order.getOrderId());
                return JsonResult.ok();
            } else {
                log.warn("更新订单失败: ID={}", order.getOrderId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "更新订单失败");
            }
        } catch (Exception e) {
            log.error("更新订单失败: ID={}", order.getOrderId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新订单失败");
        }
    }
}
